/**
 * 智能营养管理系统 - 主要JavaScript文件
 */

// 全局配置
const App = {
    config: {
        apiBaseUrl: '/api',
        chartColors: {
            primary: '#007bff',
            success: '#28a745',
            info: '#17a2b8',
            warning: '#ffc107',
            danger: '#dc3545',
            secondary: '#6c757d'
        }
    },
    
    // 初始化应用
    init: function() {
        this.initTooltips();
        this.initAlerts();
        this.bindGlobalEvents();
        console.log('智能营养管理系统已初始化');
    },
    
    // 初始化工具提示
    initTooltips: function() {
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    },
    
    // 初始化警告框自动关闭
    initAlerts: function() {
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => {
            if (alert.classList.contains('alert-success')) {
                setTimeout(() => {
                    const bsAlert = new bootstrap.Alert(alert);
                    bsAlert.close();
                }, 5000);
            }
        });
    },
    
    // 绑定全局事件
    bindGlobalEvents: function() {
        // 点餐按钮事件
        document.addEventListener('click', (e) => {
            if (e.target.matches('.btn-order') || e.target.closest('.btn-order')) {
                e.preventDefault();
                const btn = e.target.matches('.btn-order') ? e.target : e.target.closest('.btn-order');
                this.handleOrderClick(btn);
            }

            // 收藏按钮事件
            if (e.target.matches('.btn-favorite') || e.target.closest('.btn-favorite')) {
                e.preventDefault();
                const btn = e.target.matches('.btn-favorite') ? e.target : e.target.closest('.btn-favorite');
                this.handleFavoriteClick(btn);
            }
        });

        // 表单验证
        const forms = document.querySelectorAll('.needs-validation');
        forms.forEach(form => {
            form.addEventListener('submit', this.handleFormValidation);
        });
        
        // AJAX表单提交
        const ajaxForms = document.querySelectorAll('.ajax-form');
        ajaxForms.forEach(form => {
            form.addEventListener('submit', this.handleAjaxForm);
        });
    },
    
    // 处理表单验证
    handleFormValidation: function(event) {
        if (!this.checkValidity()) {
            event.preventDefault();
            event.stopPropagation();
        }
        this.classList.add('was-validated');
    },
    
    // 处理AJAX表单提交
    handleAjaxForm: function(event) {
        event.preventDefault();
        const form = this;
        const formData = new FormData(form);
        const url = form.action;
        const method = form.method || 'POST';
        
        App.showLoading(form);
        
        fetch(url, {
            method: method,
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            App.hideLoading(form);
            if (data.success) {
                App.showMessage('success', data.message || '操作成功');
                if (data.redirect) {
                    setTimeout(() => {
                        window.location.href = data.redirect;
                    }, 1000);
                }
            } else {
                App.showMessage('error', data.message || '操作失败');
            }
        })
        .catch(error => {
            App.hideLoading(form);
            App.showMessage('error', '网络错误，请稍后重试');
            console.error('AJAX错误:', error);
        });
    },
    
    // 显示加载状态
    showLoading: function(element) {
        const button = element.querySelector('button[type="submit"]');
        if (button) {
            button.disabled = true;
            const originalText = button.innerHTML;
            button.setAttribute('data-original-text', originalText);
            button.innerHTML = '<span class="loading"></span> 处理中...';
        }
    },
    
    // 隐藏加载状态
    hideLoading: function(element) {
        const button = element.querySelector('button[type="submit"]');
        if (button) {
            button.disabled = false;
            const originalText = button.getAttribute('data-original-text');
            if (originalText) {
                button.innerHTML = originalText;
            }
        }
    },
    
    // 显示消息
    showMessage: function(type, message) {
        const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
        const icon = type === 'success' ? 'fas fa-check-circle' : 'fas fa-exclamation-circle';
        
        const alertHtml = `
            <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
                <i class="${icon} me-2"></i>${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        
        // 查找消息容器或创建一个
        let messageContainer = document.querySelector('.message-container');
        if (!messageContainer) {
            messageContainer = document.createElement('div');
            messageContainer.className = 'message-container';
            document.querySelector('main').prepend(messageContainer);
        }
        
        messageContainer.innerHTML = alertHtml;
        
        // 自动关闭成功消息
        if (type === 'success') {
            setTimeout(() => {
                const alert = messageContainer.querySelector('.alert');
                if (alert) {
                    const bsAlert = new bootstrap.Alert(alert);
                    bsAlert.close();
                }
            }, 3000);
        }
    },
    
    // 确认对话框
    confirm: function(message, callback) {
        if (confirm(message)) {
            callback();
        }
    },
    
    // 格式化数字
    formatNumber: function(number, decimals = 1) {
        return parseFloat(number).toFixed(decimals);
    },
    
    // 格式化日期
    formatDate: function(date, format = 'YYYY-MM-DD') {
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        
        switch (format) {
            case 'YYYY-MM-DD':
                return `${year}-${month}-${day}`;
            case 'MM/DD/YYYY':
                return `${month}/${day}/${year}`;
            case 'DD/MM/YYYY':
                return `${day}/${month}/${year}`;
            default:
                return `${year}-${month}-${day}`;
        }
    }
};

// 营养相关工具函数
const Nutrition = {
    // 计算BMI
    calculateBMI: function(height, weight) {
        if (!height || !weight) return 0;
        const heightInMeters = height / 100;
        return weight / (heightInMeters * heightInMeters);
    },
    
    // 获取BMI状态
    getBMIStatus: function(bmi) {
        if (bmi < 18.5) return { status: '偏瘦', class: 'text-info' };
        if (bmi < 24) return { status: '正常', class: 'text-success' };
        if (bmi < 28) return { status: '超重', class: 'text-warning' };
        return { status: '肥胖', class: 'text-danger' };
    },
    
    // 计算BMR (基础代谢率)
    calculateBMR: function(height, weight, age, gender) {
        if (!height || !weight || !age || !gender) return 0;
        
        if (gender === 'MALE') {
            return 10 * weight + 6.25 * height - 5 * age + 5;
        } else {
            return 10 * weight + 6.25 * height - 5 * age - 161;
        }
    },
    
    // 计算TDEE (总能量消耗)
    calculateTDEE: function(bmr, activityLevel) {
        const multipliers = {
            'SEDENTARY': 1.2,
            'LIGHT': 1.375,
            'MODERATE': 1.55,
            'ACTIVE': 1.725,
            'VERY_ACTIVE': 1.9
        };
        
        return bmr * (multipliers[activityLevel] || 1.55);
    },
    
    // 计算营养比例
    calculateNutritionRatio: function(protein, carbs, fat) {
        const proteinCalories = protein * 4;
        const carbsCalories = carbs * 4;
        const fatCalories = fat * 9;
        const totalCalories = proteinCalories + carbsCalories + fatCalories;
        
        if (totalCalories === 0) return { protein: 0, carbs: 0, fat: 0 };
        
        return {
            protein: (proteinCalories / totalCalories * 100).toFixed(1),
            carbs: (carbsCalories / totalCalories * 100).toFixed(1),
            fat: (fatCalories / totalCalories * 100).toFixed(1)
        };
    },
    
    // 获取营养目标完成度颜色
    getProgressColor: function(percentage) {
        if (percentage < 50) return 'bg-danger';
        if (percentage < 80) return 'bg-warning';
        if (percentage <= 100) return 'bg-success';
        return 'bg-info';
    }
};

// 图表工具函数
const Charts = {
    // 创建营养进度环形图
    createNutritionDonutChart: function(canvasId, data) {
        const ctx = document.getElementById(canvasId).getContext('2d');
        
        return new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: ['蛋白质', '碳水化合物', '脂肪'],
                datasets: [{
                    data: [data.protein, data.carbs, data.fat],
                    backgroundColor: [
                        App.config.chartColors.warning,
                        App.config.chartColors.info,
                        App.config.chartColors.success
                    ],
                    borderWidth: 2,
                    borderColor: '#fff'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
    },
    
    // 创建营养趋势折线图
    createNutritionTrendChart: function(canvasId, data) {
        const ctx = document.getElementById(canvasId).getContext('2d');
        
        return new Chart(ctx, {
            type: 'line',
            data: {
                labels: data.labels,
                datasets: [{
                    label: '卡路里',
                    data: data.calories,
                    borderColor: App.config.chartColors.danger,
                    backgroundColor: App.config.chartColors.danger + '20',
                    tension: 0.4
                }, {
                    label: '蛋白质',
                    data: data.protein,
                    borderColor: App.config.chartColors.warning,
                    backgroundColor: App.config.chartColors.warning + '20',
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                },
                plugins: {
                    legend: {
                        position: 'top'
                    }
                }
            }
        });
    },

    // 处理点餐按钮点击
    handleOrderClick: function(btn) {
        const dishId = btn.dataset.dishId;
        const dishName = btn.dataset.dishName;
        const mealType = btn.dataset.mealType || this.getCurrentMealType();

        if (!dishId) {
            this.showMessage('error', '菜品信息错误');
            return;
        }

        this.showPortionModal(dishId, dishName, mealType);
    },

    // 显示份量选择模态框
    showPortionModal: function(dishId, dishName, mealType) {
        const modalHtml = `
            <div class="modal fade" id="portionModal" tabindex="-1">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">选择份量 - ${dishName}</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <div class="mb-3">
                                <label class="form-label">餐别</label>
                                <select class="form-select" id="mealTypeSelect">
                                    <option value="BREAKFAST" ${mealType === 'BREAKFAST' ? 'selected' : ''}>早餐</option>
                                    <option value="LUNCH" ${mealType === 'LUNCH' ? 'selected' : ''}>午餐</option>
                                    <option value="DINNER" ${mealType === 'DINNER' ? 'selected' : ''}>晚餐</option>
                                    <option value="SNACK" ${mealType === 'SNACK' ? 'selected' : ''}>小食</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">份量</label>
                                <div class="input-group">
                                    <button class="btn btn-outline-secondary" type="button" onclick="App.adjustPortion(-0.5)">-</button>
                                    <input type="number" class="form-control text-center" id="portionInput"
                                           value="1.0" min="0.5" max="5.0" step="0.5">
                                    <button class="btn btn-outline-secondary" type="button" onclick="App.adjustPortion(0.5)">+</button>
                                </div>
                                <small class="text-muted">建议份量：0.5-5.0份</small>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                            <button type="button" class="btn btn-primary" onclick="App.confirmOrder(${dishId})">确认点餐</button>
                        </div>
                    </div>
                </div>
            </div>
        `;

        const existingModal = document.getElementById('portionModal');
        if (existingModal) {
            existingModal.remove();
        }

        document.body.insertAdjacentHTML('beforeend', modalHtml);
        const modal = new bootstrap.Modal(document.getElementById('portionModal'));
        modal.show();
    },

    // 调整份量
    adjustPortion: function(change) {
        const input = document.getElementById('portionInput');
        const currentValue = parseFloat(input.value) || 1.0;
        const newValue = Math.max(0.5, Math.min(5.0, currentValue + change));
        input.value = newValue.toFixed(1);
    },

    // 确认点餐
    confirmOrder: function(dishId) {
        const mealType = document.getElementById('mealTypeSelect').value;
        const portion = parseFloat(document.getElementById('portionInput').value);

        if (!mealType || !portion || portion < 0.5) {
            this.showMessage('error', '请选择正确的餐别和份量');
            return;
        }

        fetch('/nutrition/order', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                dishId: dishId,
                mealType: mealType,
                portionSize: portion
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                this.showMessage('success', data.message);
                const modal = bootstrap.Modal.getInstance(document.getElementById('portionModal'));
                modal.hide();

                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            } else {
                this.showMessage('error', data.message);
            }
        })
        .catch(error => {
            this.showMessage('error', '点餐失败，请稍后重试');
            console.error('Error:', error);
        });
    },

    // 处理收藏按钮
    handleFavoriteClick: function(btn) {
        const dishId = btn.dataset.dishId;
        const isFavorited = btn.classList.contains('favorited');

        btn.classList.toggle('favorited');
        const icon = btn.querySelector('i');
        if (icon) {
            icon.classList.toggle('fas');
            icon.classList.toggle('far');
        }

        this.showMessage('success', isFavorited ? '已取消收藏' : '已添加收藏');
    },

    // 获取当前餐别
    getCurrentMealType: function() {
        const hour = new Date().getHours();
        if (hour >= 7 && hour < 11) return 'BREAKFAST';
        if (hour >= 11 && hour < 15) return 'LUNCH';
        if (hour >= 17 && hour < 21) return 'DINNER';
        return 'SNACK';
    }
};

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', function() {
    App.init();
});

// 导出全局对象
window.App = App;
window.Nutrition = Nutrition;
window.Charts = Charts;
